﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using NLog;

namespace Jet.VersionIncrementor
{
	/// <summary>
	/// Parse solution file and find project files.
	/// </summary>
	internal class SolutionParser
	{
		private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
		/// <summary>
		/// .ctor
		/// </summary>
		/// <param name="solutionFileName">Path to solution file</param>
		public SolutionParser(string solutionFileName)
		{
			Projects = Parse(solutionFileName); 			
		}

		/// <summary>
		/// Project included in solution. For now onle C# projects supported.
		/// </summary>
		public IEnumerable<BaseProjectParser> Projects { get; private set; }

		private static IEnumerable<BaseProjectParser> Parse(string solutionFileName)
		{
			if (string.IsNullOrEmpty(solutionFileName))
			{
				throw new ArgumentNullException("solutionFileName");
			}
			_logger.Debug("Parsing project '{0}'", solutionFileName);
			var result = new List<BaseProjectParser>();
			var solution = File.ReadAllText(solutionFileName);
			var solutionDir = Path.GetDirectoryName(solutionFileName);
			var expr = new Regex(@"Project(.*), ""(.*)"",", RegexOptions.IgnoreCase);
			var matches = expr.Matches(solution);
			foreach (Match match in matches)
			{
				var relativePath = match.Groups[2].ToString();
				var fullPath = Path.Combine(solutionDir, relativePath);
				var ext = Path.GetExtension(fullPath);
				_logger.Debug("Found project '{0}'", fullPath); 
				if (ext == ".csproj")
				{
					result.Add(new CSharpProjectParser(fullPath));
					_logger.Debug("Found project '{0}' is c# project and added to processing", fullPath);
				}
			}
			return result;
		}
	}
}
